//
//  XTUserAccountViewModel.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/12.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

class XTUserAccountViewModel: NSObject {

    //保存用户对象
    var userAccount : XTUserAcount?
    
    
    //设置全局的单例对象
    static var sharedUserAccount:XTUserAccountViewModel = XTUserAccountViewModel()
    
    //初始化方法
    override init() {
        super.init()
        //获取已经归档了的对象
        userAccount = XTUserAcount.loadUserAcction()
    }
    
    
    var isLogin : Bool{
        
        return accessToken != nil
    
    }
    
    var accessToken:String?{
        guard let token = userAccount?.access_token else{
            //如果access_token为nil，则为未登录
            
        return nil
        }
        
        //将过期日期与当前日期相比较，若为降序（即过期日期大于当前日期），则未过期
        
        let result = userAccount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending{
        return token
        }else{
        return nil
        }
    }
    
    
    
    //封装网络接口
    
    //获取用户数据
    func requestUserInfo(userAccount:XTUserAcount,complete:(isSuccess:Bool)->()){
    XTNetWorkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
        if error != nil{
        print("网络请求异常")
            complete(isSuccess: false)
            return
        }
        
        //判断是否为JSON格式
        guard let dic = response as? [String:AnyObject] else{
        print("返回的不是一个JSON文件")
            complete(isSuccess: false)
            return
        }
        
        //若代码可以执行到此处，说明dic时一个dict类型的数据
        userAccount.name = dic["name"] as? String
        userAccount.avatar_large = dic["avatar_large"] as? String
        
        
        self.userAccount = userAccount
        
        //将用户数据进行归档
        let result = userAccount.saveUserAccount()
        
        
        if result {
        //登陆成功
            complete(isSuccess: true)
        }else{
            complete(isSuccess: false)
        }
        }
    }
    
    
    
    
    //获取access_token
    
    func requestAccessToken(code:String,complete:(isSuccess:Bool)->()){
        
        XTNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil{
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            
            //判断是否为JSON格式
            guard let dic = response as? [String:AnyObject] else{
                print("返回的不是一个JSON文件")
                complete(isSuccess: false)
                return
            }
            
            let userAccouent = XTUserAcount(dic: dic)
            print(userAccouent)
            
            self.requestUserInfo(userAccouent, complete: complete)

        }
        
        
        
      }
}